import React, { Component, useRef } from 'react'
import { SearchOutlined } from '@ant-design/icons'
import { Form, Input, Space, Button, Select, DatePicker, Tabs } from 'antd'
import _ from 'lodash'
import TheButton from '@/components/TheButton'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheDialog from '@/components/TheDialog'
import { apiShopSalesReturnPage, apiShopSalesReturnRefundConfirm } from '@/request/orderManagement'
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from '@/utils/exportTable.js'

const { RangePicker } = DatePicker
const { TabPane } = Tabs

const SearchHeader = ({ getValue, exportDataList }) => {
  const formRef = useRef()
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0]) + ' 00:00:00'
      values.createTimeEnd = getDateTime3(values.time[1]) + ' 23:59:59'
    }
    delete values.time
    _.forIn(values, (v, k) => {
      if (!v) {
        delete values[k]
      }
    })
    getValue(values)
  }
  const onlineExportOrderDetail = () => {
    exportDataList({ option: formRef.current.getFieldValue() })
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      shopOrderId: '',
      orderCode: '',
      returnCode: '',
      moneyStatus: null,
      time: [],
    })
    getValue({})
  }
  return (
    <Form ref={formRef} onFinish={onFinish} layout="inline">
      {/* <Form.Item name="shopOrderId">
        <Input
          style={{ width: 140 }}
          placeholder="请输入订单号"
          suffix={<SearchOutlined />}
        />
      </Form.Item> */}
      <Form.Item name="orderCode">
        <Input
          style={{ width: 140 }}
          placeholder="请输入订单编号"
          suffix={<SearchOutlined />}
        />
      </Form.Item>
      <Form.Item name="returnCode">
        <Input
          style={{ width: 140 }}
          placeholder="请输入退单号"
          suffix={<SearchOutlined />}
        />
      </Form.Item>
      <Form.Item name="moneyStatus">
        <Select
          options={[
            {
              value: 'N',
              label: '仅退款',
            },
            {
              value: 'Y',
              label: '退货退款',
            },
          ]}
          placeholder={'请选择退款类型'}
          width={160}
        />
      </Form.Item>
      <Form.Item name="time">
        <RangePicker placeholder={['申请时间', '申请时间']} />
      </Form.Item>
      <Form.Item>
        <Space>
          <Button htmlType="submit" type="primary">
            搜索
          </Button>
          <Button onClick={reset}>重置</Button>
        </Space>
      </Form.Item>
      <TheButton
        haspermi={['mallchargeback:list:export']}
        type="default"
        size="middle"
        onClick={onlineExportOrderDetail}
      >
        导出全部
      </TheButton>
    </Form>
  )
}

export default class MallChangeback extends Component {
  roleIds = sessionStorage.getItem('roleName')

  state = {
    columns: [
      // {
      //   title: '订单号',
      //   dataIndex: 'shopOrderId',
      //   key: 'shopOrderId',
      // },
      {
        title: '订单编号',
        dataIndex: 'orderCode',
        key: 'orderCode',
      },
      {
        title: '退单编号',
        dataIndex: 'returnCode',
        key: 'returnCode',
      },
      {
        title: '买家昵称',
        dataIndex: 'nickName',
        key: 'nickName',
      },
      {
        title: '退款商品',
        dataIndex: 'goodsName',
        key: 'goodsName',
        render: (text, record) => {
          let goodsSku = JSON.parse(record.goodsSkuJson)
          let arr = _.toArray(_.toArray(goodsSku).skuAttribute).map((v) => {
            return v.value
          })
          return (
            <div>
              <div>{text}</div>
              <div>{arr}</div>
            </div>
          )
        },
      },
      {
        title: '商家名称',
        dataIndex: 'storeName',
        key: 'storeName',
      },
      {
        title: '退款类型',
        dataIndex: 'moneyStatus',
        key: 'moneyStatus',
        render: (text, record) => {
          let label = ''
          switch (text) {
            case 'N':
              label = '仅退款'
              break
            case 'Y':
              label = '退货退款'
              break
          }
          return label
        },
      },
      {
        title: '订单金额（元）',
        dataIndex: 'orderPrice',
        key: 'orderPrice',
        render: (text, record) => {
          return <React.$Price price={text} />
        },
      },
      {
        title: '实付金额（元）',
        dataIndex: 'detailPayPrice',
        key: 'detailPayPrice',
        render: (text, record) => {
          return <React.$Price price={text} />
        },
      },
      {
        title: '退款金额（元）',
        dataIndex: 'detailPayPrice',
        key: 'detailPayPrice',
        render: (text, record) => {
          return <React.$Price price={text} />
        },
      },
      {
        title: '申请时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '退款状态',
        dataIndex: 'salesStatus',
        key: 'salesStatus',
        render: (text, record) => {
          let label = ''
          switch (parseInt(text)) {
            case 1:
              label = '退款中'
              break
            case 2:
              label = '退款中'
              break
            case 3:
              label = '退款中'
              break
            case 4:
              label = '退款失败'
              break
            case 9:
              label = '退款成功'
              break
            case 0:
              label = '退款关闭'
              break
          }
          return label
        },
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record) => {
          return (
            <>
              <TheButton haspermi={['order:mallChargeback:detail']}
                onClick={() =>
                  this.props.history.push(
                    `/order/chargeback/mallDetails/${record.shopSalesReturnId}`
                  )
                }>
                查看订单
              </TheButton>
              {/* {parseInt(record.salesStatus) === 4 && !this.roleIds.includes('客服') && (
                <TheButton haspermi={['order:mallChargeback:refund']} onClick={() => { this.refundSubmit(record.shopSalesReturnId) }}
                >退款</TheButton>
              )} */}
              {parseInt(record.salesStatus) === 4 && (
                <TheButton haspermi={['order:mallChargeback:refund']} onClick={() => { this.refundSubmit(record.shopSalesReturnId) }}
                >退款</TheButton>
              )}
            </>
          )
        },
      },
    ],
    dataSource: [],
    tabData: [
      {
        key: 1,
        tab: '退款中',
      },
      {
        key: 9,
        tab: '退款成功',
      },
      {
        key: 4,
        tab: '退款失败',
      },
      {
        key: 0,
        tab: '退款关闭',
      },
    ],
    pageData1: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData9: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData4: {
      pageNo: 1,
      pageSize: 10,
    },
    pageData0: {
      pageNo: 1,
      pageSize: 10,
    },
    total1: 0,
    total9: 0,
    total4: 0,
    total0: 0,
    searchValue: {},
    salesStatus: 1,
  }
  componentDidMount() {
    this.getData()
  }
  refundSubmit = (ReturnId) => {
    console.log(ReturnId)
    React.$confirm({
      title: "您确认对此订单进行退款操作吗？",
      onOk: async () => {
        this.setState({ loading: true })
        let params = {
          shopSalesReturnId: ReturnId
        }
        let res = await apiShopSalesReturnRefundConfirm({ ...params })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '退款成功'
          })
          this.getData()
        }
      },
    });
  }

  getData = async () => {
    const { searchValue, salesStatus } = this.state
    let res = await apiShopSalesReturnPage({
      salesStatus,
      ...searchValue,
      ...this.state[`pageData${salesStatus}`],
    })
    console.log(res.data)
    if (res.code === 0 && res.data) {
      this.setState({
        dataSource: res.data,
        [`pageData${salesStatus}`]: {
          pageNo: res.pageNo,
          pageSize: res.pageSize,
        },
        [`total${salesStatus}`]: res.totalCount,
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    const { salesStatus } = this.state
    this.setState(
      {
        [`pageData${salesStatus}`]: {
          pageNo,
          pageSize,
        },
      },
      () => {
        this.getData()
      }
    )
  }
  getValue = (value) => {
    const { salesStatus } = this.state
    this.setState(
      {
        [`pageData${salesStatus}`]: {
          pageNo: 1,
          pageSize: 10,
        },
        searchValue: value,
      },
      () => {
        this.getData()
      }
    )
  }
  changeKey = (key) => {
    this.setState(
      {
        salesStatus: key,
      },
      () => {
        this.getData()
      }
    )
  }

  exportAll = async (e) => {
    const { searchValue, salesStatus } = this.state
    let res = await apiShopSalesReturnPage({ ...searchValue, salesStatus, pageNo: 1, pageSize: 100, type: "Y", })
    if (res.code === 0 && res.data) {
      console.log(res.data);
      const th_arr = [
        {
          title: '商城退单列表',
          prop: '',
          children: [
            {
              title: '订单编号',
              prop: 'orderCode',
            },
            {
              title: '退单编号',
              prop: 'returnCode',
            },
            {
              title: '买家昵称',
              prop: 'nickName',
            },
            {
              title: '退款商品',
              prop: 'goodsName',
            },
            {
              title: '商家名称',
              prop: 'storeName',
            },
            {
              title: '退款类型',
              prop: 'moneyStatus',
            },
            {
              title: '订单金额（元）',
              prop: 'orderPrice',
              valueType:'number'
            },
            {
              title: '实付金额（元）',
              prop: 'detailPayPrice',
              valueType:'number'
            },
            {
              title: '退款金额（元）',
              prop: 'detailPayPrice',
              valueType:'number'
            },
            {
              title: '申请时间',
              prop: 'createTime',
            },
            {
              title: '退款状态',
              prop: 'salesStatus',
            },
          ]
        },

      ]
      let tb_arr = []
      res.data.forEach(item => {
        tb_arr.push({
          orderCode: item.orderCode || '/',
          returnCode:item.returnCode || '/',
          nickName: item.nickName || '/',
          goodsName: item.goodsName || '/',
          storeName: item.storeName || '/',
          moneyStatus: item.moneyStatus ==="N" ? "仅退款" :"退货退款",
          orderPrice: Number(item.orderPrice / 100).toFixed(2) || '/',
          detailPayPrice: Number(item.detailPayPrice / 100).toFixed(2) || '/',
          detailPayPrice: Number(item.detailPayPrice / 100).toFixed(2) || '/',
          createTime: item.createTime || '/',
          salesStatus: item.salesStatus === '1' ? "退款中" : item.salesStatus === '4' ? "退款失败" : item.salesStatus === '9' ? "退款成功" : item.salesStatus === '0' ? "退款关闭" : ""
        })
      })
      exportSheetTable({ fileName: `商城订单${salesStatus === '1' ? "退款中" : salesStatus === '4' ? "退款失败" : salesStatus === '9' ? "退款成功" : salesStatus === '0' ? "退款关闭" : ""}`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
    }
  }

  render() {
    const { columns, tabData, dataSource } = this.state
    return (
      <div className="p-layout-box">
        <Tabs
          onChange={this.changeKey}
          tabBarExtraContent={<SearchHeader getValue={this.getValue} exportDataList={() => this.exportAll()} />}>
          {tabData.map((v) => {
            return (
              <TabPane key={v.key} tab={v.tab}>
                <div className="p-layout-content-pagination">
                  <TheTable
                    scroll={{ x: 'max-content', y: '58vh' }}
                    columns={columns}
                    dataSource={dataSource}
                  />
                  <ThePagination
                    pageNo={this.state[`pageData${v.key}`].pageNo}
                    pageSize={this.state[`pageData${v.key}`].pageSize}
                    total={this.state[`total${v.key}`]}
                    pageChange={this.pageChange}
                  />
                </div>
              </TabPane>
            )
          })}
        </Tabs>
      </div>
    )
  }
}
